<template>
  <div class="p-2">
    <el-card shadow="hover">
      <div>
        <h3><span style="font-size: 20px; color: red;"></span></h3>
        <!-- 返回按钮，控制了返回按钮的显示与隐藏 -->
        <a id="back" href="javascript:;" v-show="showBackButton" @click="goBack" class="center-btn">返回</a>
        <!-- 设置id为main的地图容器-->
        <div id="main2" style="height: 800px"></div>
      </div>
    </el-card>
  </div>
</template>



<script setup>
//响应式数据  ref(创建响应式数据)
//              onMounted(生命周期钩子,组件挂载完成后执行相应逻辑)
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { allNyt7PolicyInsurance } from '@/api/Nyt7PolicyInsurance/Nyt7PolicyInsurance/index.ts';
//import axios from 'axios';
//布尔类型的响应数据,控制页面返回按钮显示状态
const showBackButton = ref(false);
// 存储初始化得到echarts图
const myChart = ref(null);
// 地图层级
const mapList = ref([]);

//各省份的数据
let allData;

//数据获取与相关逻辑函数
const getJSON = async ({ name }, callback) => {
  console.log(name);
  //map路径地址
  const url = `/map2/${name}.json`;
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
    callback(data);
    console.log(data);
    setBackbtn({ name });
  } catch (error) {
    alert('无此区域地图显示，请查看其他区域！');
  }
};

//接受name后的操作
const setBackbtn = ({ name }) => {
  mapList.value.push({ name });
  showBackButton.value = name !== 'hebei2';
  console.log(JSON.stringify(mapList.value));
};


//实现地图返回上一级的功能
const goBack = () => {
  if (mapList.value.length >= 2) {
    const { name } = mapList.value[mapList.value.length - 2];
    mapList.value.splice(-2, 2);

    getJSON({ name }, (data) => {
      renderChart(name, data);
      showBackButton.value = mapList.value.length > 0; // 当mapList长度大于0，说明不是第一级，显示返回
    });
  }
};
//初始化地图函数
const initChinaMap = () => {
  mapList.value = [];
  getJSON({ name: 'hebei2' }, (data) => {
    
    renderChart('hebei2', data);
    console.log('1',data);
    if (mapList.value.length === 0) {
      showBackButton.value = false; // 当mapList为空，也就是第一级时隐藏返回按钮
    }
  });
};

//该函数接受区域名称name和相应的data
const renderChart = (name, data) => {
  
  echarts.registerMap(name, data);
  
  setOption(name, data); // 确保传递的是保单数据
};


async function getAllData() {
  allData = await allNyt7PolicyInsurance();
}

//配置地图图标的配置选项对象option
const setOption = (name, data) => {

  const totalContractAreas = allData.map(region => region.totalContractArea);
  const minTotalContractArea = Math.min(...totalContractAreas);
  const maxTotalContractArea = Math.max(...totalContractAreas);

  const chartData = allData.map(region => ({
    name: region.plotDetailInfo.city,
    value: region.totalContractArea
  }));

  const option = {
    tooltip: {
      show: true,
      formatter: function (params) {
        console.log('params', params);

        let regionInfo = allData.find((region) => region.plotDetailInfo.city === params.name);
        console.log('regionInfo', allData);
        if (regionInfo){
          return `
          地区：${params.name}<br>
          投保总面积：${regionInfo?.totalContractArea}<br>
          投保总户数：${regionInfo?.totalInsuredHouseholds}<br>
          保费总额：${regionInfo?.totalPremium}<br>
          用户自缴总额：${regionInfo?.totalSelfPaidByUser}<br>
          中央财政补贴总额：${regionInfo?.totalCentralFiscalSubsidy}<br>
          省级财政补贴总额：${regionInfo?.totalProvincialFiscalSubsidy}<br>
          地市财政补贴总额：${regionInfo?.totalMunicipalFiscalSubsidy}<br>
          区县财政补贴总额：${regionInfo?.totalDistrictAndCountyFiscalSubsidy}<br>
          其他财政补贴总额：${regionInfo?.totalOtherFiscalSubsidies}<br>
        `;
        } else {
          regionInfo = allData.find((region) => region.plotDetailInfo.districtCounty === params.name);
          if (regionInfo) {
            return `
          地区：${params.name}<br>
          投保总面积：${regionInfo?.totalContractArea}<br>
          投保总户数：${regionInfo?.totalInsuredHouseholds}<br>
          保费总额：${regionInfo?.totalPremium}<br>
          用户自缴总额：${regionInfo?.totalSelfPaidByUser}<br>
          中央财政补贴总额：${regionInfo?.totalCentralFiscalSubsidy}<br>
          省级财政补贴总额：${regionInfo?.totalProvincialFiscalSubsidy}<br>
          地市财政补贴总额：${regionInfo?.totalMunicipalFiscalSubsidy}<br>
          区县财政补贴总额：${regionInfo?.totalDistrictAndCountyFiscalSubsidy}<br>
          其他财政补贴总额：${regionInfo?.totalOtherFiscalSubsidies}<br>
        `;
          }
        }
      }

    },

    visualMap: {
      type: 'continuous',
      text: ['高', '低'],
      showLabel: true,
      left: 'right', // 右侧
      orient: 'vertical', // 垂直布局
      // min: minTotalContractArea,
      // max: maxTotalContractArea,
      
      inRange: {
        color: ['#edfbfb', '#b7d6f3', '#40a9ed', '#3598c1', '#215096']
      },
      splitNumber: 0
    },

    series: [{
      name: 'MAP',
      type: 'map',
      mapType: name,
      selectedMode: 'single', // 是否允许选中多个区域
      label: {
        normal: {
          show: true
        },
        emphasis: {
          show: true
        }
      },
      data: chartData
    }]
  };

  myChart.value.setOption(option, true);
};



//生命周期钩子
onMounted(async () => {
  //初始化echarts实例,让其与页面上id为main的DOM元素
  // (<template>中定义的地图容器关联),后续 Echarts 生成的地图就能在该容器内正确渲染展示了，
  // 为地图的可视化提供了基础支持。
  await getAllData();
  myChart.value = echarts.init(document.getElementById('main2'));
  myChart.value.on('click', (params) => {
    if (params.data) {
      const { name, level } = params.data;
      if (level === 'district') {
        alert('无此区域地图显示！');
        initChinaMap();
        return;
      }
      getJSON({ name }, (data) => {
        renderChart(name, data);
      });

    }
  });
  initChinaMap();
});
</script>




<style scoped>
/* 整体居中样式 */
/* body {
  text-align: center;
} */


/* 返回键居中 */

.center-btn {
  display: inline-block;
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
  transition: background-color 0.3s ease;
}

.center-btn:hover {
  background-color: #0056b3;
}

</style>
